// package-activity/pages/store-activity-preview/index.js
import { navTo, showLoading, hideLoading, redirectTo } from '../../../common/env';
import { PACKAGE_STORE_PAGE, PACKAGE_ACTIVITY_PAGE } from '../../../constants/route';
import { ACTIVITY_OWNER_VALUE, SALES_TYPE_VALUE } from '../../../constants/activity';
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { getActivityDetail, publishActivity, getEndorsement } from '../../../api/sto';
let loaded = false, storeId, activityId;

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        ownerInfo: {},
        activityInfo: {},
        isHasSpokes: true,
    },
    onLoad(options) {
        storeId = options.storeId;
        activityId = options.activityId;
    },
    onShow() {
        this._handleGetDetail();
    },
    async _handleGetDetail() {
        !loaded && showLoading('加载中...');
        const ownerInfo = this.data.manageTargetInfo;
        const activityInfo = await getActivityDetail({ storeId, activityId });
        this.setData({ ownerInfo, activityInfo });
        this._handleGetSpokesInfo();
        if (!loaded) hideLoading(); loaded = true;
    },
    async _handleGetSpokesInfo() {
        const { manageTargetInfo, activityInfo } = this.data;
        if (activityInfo.saleMode !== SALES_TYPE_VALUE.only_store_selling) {
            const endorsementInfo = await getEndorsement();
            this.setData({
                isHasSpokes: !endorsementInfo.isOpen && !manageTargetInfo.spokesmanCount ? false : true,
            });
        }
    },
    handleNavToSpokesman() {
        navTo(PACKAGE_STORE_PAGE['storeSpokesman']);
    },
    async handlePublish() {
        const { activityInfo } = this.data;
        showLoading('发布中...');
        const flag = await publishActivity({
            storeId: storeId || activityInfo.storeId,
            activityId: activityId || activityInfo.activityId,
        });
        if (flag) {
            hideLoading();
            redirectTo(PACKAGE_ACTIVITY_PAGE['detail'], {
                owner: ACTIVITY_OWNER_VALUE.store,
                activityId: activityId || activityInfo.activityId,
                showSuccess: true,
            });
        }
    },
    handleNavBack() {
        const { activityInfo } = this.data;
        redirectTo(PACKAGE_ACTIVITY_PAGE['storeActivityEdit'], {
            storeId: storeId || activityInfo.storeId,
            activityId: activityId || activityInfo.activityId,
        });
    },
})
